package ru.pb.auth.network.protokol;

import java.nio.ByteOrder;

import org.apache.log4j.Logger;

import ru.pb.global.configs.DevelopConfig;
import ru.pb.global.crypt.BitRotate;
import ru.pb.global.network.engine.NioSession;
import ru.pb.global.network.engine.buffer.NioBuffer;
import ru.pb.global.network.engine.core.Protocol;
import ru.pb.global.network.utils.NetworkUtil;

/**
 * @author: Felixx
 */
public class AuthProtocol implements Protocol
{
	private final Logger _log = Logger.getLogger(AuthProtocol.class);

	@Override
	public NioBuffer decode(NioSession session, NioBuffer buf)
	{
		int limit = buf.limit();
		int clientId = session.getClient().getId();
		int cryptKey = session.getClient().getCryptKey();
		int shift = session.getClient().getShift();

		if(shift <= 0)
		{
			shift = ((clientId + cryptKey) % 7) + 1;
			session.getClient().setShift(shift);
			_log.info("NEW key: " + shift);
		}
		byte[] bytes = buf.array();

		_log.info("clientId: " + clientId + "; cryptKey: " + cryptKey + "; shift: " + shift);
		bytes = BitRotate.decrypt(bytes, shift);
		_log.info("NEW BYTES:\n" + NetworkUtil.printData(bytes));

		buf = NioBuffer.allocate(bytes.length);
		buf.order(ByteOrder.LITTLE_ENDIAN);
		buf.clear();
		buf.put(bytes, 0, bytes.length);
		buf.flip();

		if(DevelopConfig.NETWORK_DEBUG)
		{
			_log.info("Принимаем байт: " + limit + " Размер пакета: " + (limit - 4));
			_log.info("INFO:\n" + NetworkUtil.printData(buf));
		}
		return buf;
	}

	@Override
	public void encode(NioSession session, NioBuffer buf)
	{
		if(DevelopConfig.NETWORK_DEBUG)
		{
			_log.info("Отправляем:" + buf.limit());
			_log.info("INFO:\n" + NetworkUtil.printData(buf));
		}
	}
}